#!/usr/bin/env python2

import os
import sys
import socket
import time
import subprocess
import fcntl
import types
import errno
import getopt
import random

from config import Config
from utils import Exp, _dmsg, _dwarn, _derror, _str2dict, _getrack

class LocalFs:
    def __init__(self, home):
        self.home = home
        self.types = ['root', 'meta', 'namespace', 'bucket', 'object', 'raw', 'node']

    def build_chunk_list(self, chunk_type = None):
        if (chunk_type == None):
            types = self.types
        else:
            if ((chunk_type in self.types) == False):
                raise Exp(errno.EINVAL, "not support %s" %(chunk_type))
            else:
                types = [chunk_type]

        res = {}
        for t in types:
            res[t] = self.__build_list(t)

        return res

    def __build_list(self, t):
        path = self.home + '/chunk/' + t
        head = []
        self.__iterator(head, path, t)
        return head

    def __iterator(self, head, path, t):
        try:
            ls = os.listdir(path)
        except OSError as err:
            if err.errno != errno.ENOENT:
                raise
            else:
                return head

        t1 = '.' + t
        l = len(t1)
        for i in ls:
            new = os.path.join(path, i)
            if (os.path.isdir(new)):
                self.__iterator(head, new, t)
            elif (new[(0 - l):] == t1):
                head.append(new)

        return head

def usage():
    print ("usage:")
    print (sys.argv[0] + " --iterator <path>")
    print (sys.argv[0])

def main():
    op = ''
    ext = None
    try:
        opts, args = getopt.getopt(
                sys.argv[1:], 
                'h', ['iterator=', 'help']
                )
    except getopt.GetoptError, err:
        print str(err)
        usage()

    for o, a in opts:
        if o in ('--help'):
            usage()
            exit(0)
        elif o == '--iterator':
            op = '--iterator'
            ext = a
        else:
            assert False, 'oops, unhandled option: %s, -h for help' % o
            exit(1)

    config = Config()
    storage = Storage(config)
    localfs = LocalFs(ext)
    if (op == '--iterator'):
        lst = localfs.build_chunk_list()
        for (k, v) in lst.items():
            print ("%s:" % k)
            for i in v:
                print ("%s:%s" % (localfs.chkid(i), i))
                #print ("%s" % (i))

if __name__ == '__main__':
    if (len(sys.argv) == 1):
        usage()
    else:
        main()
